import * as types from './mutation-types'
import { setToken, removeToken, setUser, removeUser } from 'common/js/token/auth'
import {loginByUsername, logout, getUserInfo, postAccessToken} from "../api/login";

// 用户名登录
export const LoginByUsername = function({commit, state}, {username,password}) {
  username = username.trim()
  return new Promise((resolve, reject) => {
    loginByUsername(username,password).then(res => {
      commit(types.SET_TOKEN, res.auth_token)
      setToken(res.auth_token)
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })

}

// 登出 token 清空  用户信息清空
export const LogOut = function({commit, state}) {
  return new Promise((resolve, reject) => {
    logout(state.token).then((res) => {
      commit(types.SET_TOKEN, '')
      commit(types.SET_USER, null)
      removeToken()
      removeUser()
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

//前端登出

//第三方登录
export const LoginByThirdParty = function({commit, state}, network, token) {
  return new Promise((resolve, reject) => {
    postAccessToken(network, token).then(res => {
      console.log(res)
      // commit(types.SET_TOKEN, res)
      // setToken(res)
      resolve(res)
    })
    .catch(err => {
      reject(err)
    })
  })
}

//获取用户信息
export const GetUserInfo = function({commit, state}) {
  return new Promise((resolve, reject) => {
    getUserInfo().then(res => {
      commit(types.SET_USER, res)
      setUser(res)
      resolve()
    }).catch(err => {
      reject(err)
    })
  })
}

//  设置loadding
export const StartLoading = function({commit, state}, promise) {
  const startTime = new Date().getTime()
  let timer = setInterval(() => {
    if (new Date().getTime() - startTime >= 300) {
      commit(types.SET_ROUTE_LOADING, true)
      clearInterval(timer)
    }
  }, 20)
  promise().then(function() {
    clearInterval(timer)
    commit(types.SET_ROUTE_LOADING, false)
  }, function() {
    clearInterval(timer)
    commit(types.SET_ROUTE_LOADING, false)
  })
}

// 设置按钮类型的loading
export const BtnLoading = function({commit, state}, callback) {
  const startTime = new Date().getTime()
  let timer = setInterval(() => {
    if (new Date().getTime() - startTime >= 300) {
      commit(types.SET_ROUTE_LOADING, true)
      clearInterval(timer)
    }
  }, 20)
  callback(timer, commit)
}

